package camid.distribution.lifecycle;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import camid.distribution.activeobject.ObjectRegistry;
import camid.distribution.activeobject.ObjectScheduler;
import camid.distribution.events.FutureNotificator;

public class ObjectManager {

	private LifecycleBuilder lmBuilder;
	private Map<String, Class<?>> idMap;
	
	public ObjectManager(ObjectRegistry objectRegistry, FutureNotificator futureNotificator) 
	{
		lmBuilder = new LifecycleBuilder(objectRegistry, futureNotificator);
		idMap = Collections.synchronizedMap(new HashMap<String, Class<?>> ());
	}

	public void shutdown() 
	{
		lmBuilder.shutdown();
	}

	public ObjectScheduler newObject(String objectId, Class<?> entityClass) throws InstantiationException, IllegalAccessException 
	{
		idMap.put(objectId, entityClass);
		AbstractLifecycleManager alm = lmBuilder.fetchLifecycleManager(entityClass);
		ObjectScheduler scheduler = alm.newObject(objectId, entityClass, getEntityFactory());
		return scheduler;
	}

	private DefaultEntityFactory getEntityFactory() 
	{	
		return new DefaultEntityFactory();
	}

	public ObjectScheduler getObject(String objectId) 
	{
		ObjectScheduler scheduler = null;
		Class<?> entityClass = idMap.get(objectId);
		if(entityClass != null)
		{
			AbstractLifecycleManager alm = lmBuilder.fetchLifecycleManager(entityClass);
			scheduler = alm.getObject(objectId);
		}
		return scheduler;
	}

	public boolean hasObject(String objectId) 
	{
		boolean result = false;
		Class<?> entityClass = idMap.get(objectId);
		if(entityClass != null)
		{
			AbstractLifecycleManager alm = lmBuilder.fetchLifecycleManager(entityClass);
			result = alm.hasObject(objectId);
		}
		return result;
	}

	public ObjectScheduler destroyObject(String objectId) {
		ObjectScheduler scheduler = null;
		Class<?> entityClass = idMap.get(objectId);
		if(entityClass != null)
		{
			AbstractLifecycleManager alm = lmBuilder.fetchLifecycleManager(entityClass);
			scheduler = alm.destroyObject(objectId);
		}
		return scheduler;
	}

	public ObjectScheduler insertObject(String objectId, Object entity) 
			throws InstantiationException, IllegalAccessException 
	{
		AbstractLifecycleManager alm = lmBuilder.fetchLifecycleManager(entity.getClass());
		idMap.put(objectId, entity.getClass());
		ObjectScheduler scheduler = alm.insertObject(objectId, entity);
		return scheduler;
	}

	
	
	

}
